package example;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ctg.faas.runtime.Context;
import com.ctg.faas.runtime.FunctionInitializer;
import com.ctg.faas.runtime.HttpRequestHandler;
import com.ctg.faas.runtime.PreStopHandler;
import example.util.ServletUtil;

import java.io.IOException;
import java.io.OutputStream;
import java.util.logging.Logger;
import javax.servlet.ServletException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HttpApp implements HttpRequestHandler , FunctionInitializer , PreStopHandler {

    private static final Logger logger = Logger.getLogger(HttpApp.class.getName());

    @Override
    public void handleRequest(HttpServletRequest request, HttpServletResponse response, Context context)
            throws IOException, ServletException {
        String requestPath = (String) request.getAttribute("FC_REQUEST_PATH");
        String requestURI = (String) request.getAttribute("FC_REQUEST_URI");
        String requestClientIP = (String) request.getAttribute("FC_REQUEST_CLIENT_IP"); 
        
        response.setStatus(200);
        response.setHeader("header1", "value1");
        response.setHeader("header2", "value2");
        response.setHeader("Content-Type", "text/plain");
        context.getLogger().info("hello");
        logger.info("loger hello");
        String body = ServletUtil.getBodyData(request);
        JSONObject json =  JSON.parseObject(body);
        context.getLogger().info("body:"+json.toString());
        String req = String.format("Path: %s\n Uri: %s\n IP: %s\n", requestPath, requestURI, requestClientIP);
        OutputStream out = response.getOutputStream();
        out.write((req).getBytes());
        out.flush();
        out.close();
    }

    /**
     * 做一些实例初始化的工作，比如初始化
     * @param context The function compute initialize environment context object.
     * @throws IOException
     */
    @Override
    public void initialize(Context context) throws IOException {
        context.getLogger().info("init");
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        context.getLogger().info("init ok");
    }

    /**
     * 实例关停
     * @param context The function compute preStop environment context object.
     * @throws IOException
     */
    @Override
    public void preStop(Context context) throws IOException {
        context.getLogger().info("stop");
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        context.getLogger().info("stop ok");
    }
}
